package GoodsService

import (
	"context"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/request/BaseReq"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/common/response/GoodsResp"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
)

func GetActivityOptionByGoodsId(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	goodsId := gconv.Int64(req.Id)
	activityId := r.GetInt64("activity_id", 0)
	if activityId == 0 {
		return response.FailByRequestMessage(nil, "活动id不能为空")
	}
	res, err := GetActivityOptionByActivityIdGoodsIds(ctx, activityId, []int64{goodsId})
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}

	return response.SuccessByRequestMessageData(r, "成功", res)
}

func GetActivityOptionByActivityIdGoodsIds(ctx context.Context, activityId int64, goodsIds []int64) ([]*GoodsResp.GoodsActivityOption, error) {
	return GetActivityOptionByWhere(ctx, activityId, g.Map{
		"go.delete_at < ?":   1,
		"go.is_open = ?":     1,
		"go.goods_id IN (?)": goodsIds,
	})
}

func GetActivityOptionByWhere(ctx context.Context, activityId int64, where g.Map) ([]*GoodsResp.GoodsActivityOption, error) {
	fields := "go.id AS option_id,go.title,go.sell_price,gagl.goods_id,IFNULL(gagl.id,0) AS gagl_id,"
	fields += "gagl.price AS gagl_price,IFNULL(gagl.custom_stock,1) AS custom_stock,go.stock,gagl.stock AS gagl_stock"
	var res []*GoodsResp.GoodsActivityOption
	err := toolsDb.GetUnSafaTable(ctx, "goods_option").As("go").
		Fields(fields).
		LeftJoin(
			"goods_activity_goods_list gagl", "gagl.goods_option_id = go.id AND gagl.delete_at < 1 AND gagl.activity_id="+
				gconv.String(activityId)).
		Where(where).Scan(&res)
	if err != nil {
		return nil, err
	}

	return res, nil
}
